<template>
  <div class="pageDetail">
    <el-form
      ref="formRef"
      class="form_item_w2"
      :model="pageForm"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="专家姓名" prop="expertName">
        <el-select
          v-model="pageForm.expertName"
          filterable
          remote
          reserve-keyword
          placeholder="请选择专家姓名"
          :remote-method="remoteMethod"
          :loading="loading"
          :disabled="disabled"
          @change="setExpert($event)"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专家类型" prop="expertTypeId">
        <el-select v-model="pageForm.expertTypeId" placeholder="请选择专家类型" :disabled="disabled">
          <el-option 
            v-for="(dictItem,index) in expert_type" 
            :label="dictItem.dictLabel" 
            :value="dictItem.dictCode"
            :key="index" 
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专家领域" prop="expertFieldId">
        <el-select v-model="pageForm.expertFieldId" placeholder="请选择专家领域" :disabled="disabled">
          <el-option 
            v-for="(dictItem,index) in expert_field_type" 
            :label="dictItem.dictLabel" 
            :value="dictItem.dictCode"
            :key="index" 
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任聘单位" prop="organization">
        <el-input v-model="pageForm.organization" placeholder="请输入任聘单位" :disabled="disabled"></el-input>
      </el-form-item>
      <el-form-item label="工作形式" prop="workModeId">
        <el-select v-model="pageForm.workModeId" placeholder="请选择工作形式" :disabled="disabled">
          <el-option 
            v-for="(dictItem,index) in work_mode_type" 
            :label="dictItem.dictLabel" 
            :value="dictItem.dictCode"
            :key="index" 
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任聘周期" prop="startDate">
        <el-date-picker
          unlink-panels
          v-model="dateTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="(val) => changeDateRange(val)"
        />
      </el-form-item>
      <el-form-item label="职业资格证书" prop="certificateFileId">
        <FileUpload v-model="pageForm.certificateFileId" :disabled="disabled" :fileInfo="pageForm.certificateFileList"/>
      </el-form-item>
      <el-form-item label="任职状态" prop="employmentStatusId">
        <el-select v-model="pageForm.employmentStatusId" placeholder="请选择任职状态" :disabled="disabled">
          <el-option 
            v-for="(dictItem,index) in employment_status" 
            :label="dictItem.dictLabel" 
            :value="dictItem.dictCode"
            :key="index" 
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专家意见摘要" prop="opinionSummary" class="item_w1">
        <el-input 
          type="textarea" 
          v-model="pageForm.opinionSummary" 
          placeholder="请输入专家意见摘要（200字以内）" 
          :disabled="disabled"
          maxlength="200"
        ></el-input>
      </el-form-item>
      <el-form-item label=" 指导成果" prop="guidanceAchievements" class="item_w1">
        <el-input 
          type="textarea" 
          v-model="pageForm.guidanceAchievements" 
          placeholder="请输入指导成果（200字以内）" 
          :disabled="disabled"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="pageFooterBtn">
      <el-button @click="$router.back()">返回</el-button>
      <el-button type="primary" @click="handleSubmit()" v-if="['add','edit'].includes(action)" :loading="loading">提交</el-button>
    </div>
  </div>
</template>
<script>
import { rules } from './data'
import { useDict } from '@/utils/dict/useDict'
import { expertEmploymentAddApi, expertEmploymentEditApi, expertEmploymentByIdApi } from '@/api/socialServiceManage/expertEmployment'
import FileUpload from "@/components/FileUpload";
import { listUser } from "@/api/system/user";

export default {
  name: 'ParttimeRecordDetail',
  components: { FileUpload },
  data() {
    return {
      rules,
      userList: [],
      pageForm: {},
      loading: false,
      disabled: false,
      expert_type: useDict('expert_type'),
      expert_field_type: useDict('expert_field_type'),
      work_mode_type: useDict('work_mode_type'),
      employment_status: useDict('employment_status'),
      expertId: this.$route.query.expertId,
      action: this.$route.query.action,
      dateTime: []
    }
  },

  async created() {
    if (this.expertId) this.getById() // 加载详情数据
  },
  methods: {
    changeDateRange(value) {
      this.pageForm.startDate = value ? value[0] : '';
      this.pageForm.endDate = value ? value[1] : ''
    },
    remoteMethod(val) {
      let params = { userName: val, pageNum: 1, pageSize: 10 }
      listUser(params).then((response) => {
        if (response.code == 200) {
          this.userList = response.rows
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    
    setExpert(userId) {
      const user = this.userList.find(item => item.userId === userId)
      if (user) {
        this.pageForm.expertId = user.userId
        this.pageForm.expertName = user.userName
      }
    },
    
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.loading = true
        let res = {}
        if (this.expertId) {
          delete this.pageForm.fileInfo

          res = await expertEmploymentEditApi(this.pageForm)
        } else {
          res = await expertEmploymentAddApi(this.pageForm)
        }
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.$router.back()
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.log(error);
        this.$message.error('提交失败')
      } finally {
        this.loading = false
      }
    },

    // 获取兼职记录详情
    async getById() {
      if (this.action === 'look') this.disabled = true
      expertEmploymentByIdApi(this.expertId).then(res => {
        if (res.code === 200) {
          this.pageForm = res.data;
          // 回显日期范围
          this.dateTime = [
            this.pageForm.startDate || '',
            this.pageForm.endDate || ''
          ];
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  },
}
</script>
<style scoped lang="scss">
::v-deep .el-select {
	width: 100% !important;
}
::v-deep .el-date-editor{
  width: 100% !important;
}
::v-deep .el-input-number{
  width: 100% !important;
}
</style>